import * as vscode from 'vscode'
import * as querystring from 'querystring'
import { InlineGit } from './InlineGit'

export class DiffDocProvider implements vscode.TextDocumentContentProvider {
  public static scheme = 'review-mycode'

  constructor(private readonly git: InlineGit) {}

  public provideTextDocumentContent(uri: vscode.Uri): string | Thenable<string> {
    const request = decodeDiffDocUri(uri)
    if (!request.filePath || !request.commit || request.isNoExist === 'Y') {
      return ''
    }
    return this.git.getFileContentFromCommit(request).catch(() => {
      return ''
    })
  }
}

export type DiffDocUriData = {
  filePath: string
  commit: string
  isNoExist?: 'Y' | 'N'
}

export function encodeDiffDocUri(args: DiffDocUriData): vscode.Uri {
  return vscode.Uri.file(args.filePath).with({
    scheme: DiffDocProvider.scheme,
    query: querystring.stringify(args),
  })
}

export function decodeDiffDocUri(uri: vscode.Uri): DiffDocUriData {
  return querystring.parse(uri.query) as DiffDocUriData
}
